import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
// import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import java.util.Scanner;

import org.apache.commons.codec.binary.Hex;

public class MAC {
    private static final String HMAC = "Hmac";
    private static final String ALGORITHM = "SHA512";
    private static final String ENCODING = "UTF-8";
    private static final String DEFAULT_CHARSET = "US-ASCII";
    private static final String DEFAULT_KEY_GEN = "secretkey";

    public String k;
    public String t; 

    public MAC(String message, String keyGen) throws Exception {
        // KeyGenerator keyGenerator = KeyGenerator.getInstance(HMAC + ALGORITHM);
        // SecretKey secretKey = keyGenerator.generateKey();
        // Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        Mac mac = Mac.getInstance(HMAC + ALGORITHM);
        SecretKeySpec secretKey = new SecretKeySpec(keyGen.getBytes(), HMAC + ALGORITHM);

        this.k = new String(secretKey.getEncoded(), DEFAULT_CHARSET);

        mac.init(secretKey);
        byte[] M = message.getBytes(ENCODING);
        byte[] t = mac.doFinal(M);
        // return Hex.encodeHexString(t); 
        this.t = Hex.encodeHexString(t);
    }
        

    public static void main(String[] args) {
        System.out.println("Message Authentication Code Tool");
        String M, keyGen;
        if (args[0].equals("-c")) { /* check mode can be used to verify message integrity */
            try {
                Scanner scanner = new Scanner(System.in);
                System.out.print("\tM' (received message) = ");
                M = scanner.nextLine();
                System.out.print("\tt' (received tag) = ");
                String t = scanner.nextLine();
                System.out.print("\tkey generator string (or enter 'default') = ");
                keyGen = scanner.nextLine();
                if (!keyGen.equals("default")) keyGen = DEFAULT_KEY_GEN;
                MAC mac = new MAC(M, keyGen);
                System.out.println("\tt (expected tag) = " + mac.t);
                System.out.println("\tmessage untampered = " + mac.t.equals(t));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            M = args[0];
            if (args.length == 2) keyGen = args[1];
            else keyGen = DEFAULT_KEY_GEN;
             
            try { 
                MAC mac = new MAC(M, keyGen); 
                System.out.println("\tmessage = " + M);
                System.out.println("\tkey = " + mac.k);
                System.out.println("\ttag = " + mac.t);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



}
